<?php

namespace app\admin\controller;

use app\AdminBaseController;

class Role extends AdminBaseController {

    public function index(){
        if($this->request->isAjax()){
            $res = \app\admin\model\AdminRole::where([])->paginate(10, false);
            $re['rows'] = $res->items();
            $re['total'] = $res->total();
            return json($re);
        } else {
            return view();
        }
    }

    public function add(){

    }

    public function edit(){

    }

    public function del(){

    }

    // 角色已有权限
    public function getAuth(){
        if(!$this->request->isPost()) return json(['code'=>-1,'message'=>'非法请求','data'=>[]]);
        $id = $this->request->post('id',0,'intval');
        $role = \app\admin\model\AdminRoleAuth::where('role_id','=',$id)->findOrEmpty();
        $nodeIdx = [];
        if(!is_null($role->menu_idx) && strpos($role->menu_idx,',')){
            $nodeIdx = explode(',',$role->menu_idx);
        }

        array_push($nodeIdx,1);

        $all = \app\admin\model\Menus::where('pid','=',0)->field('id,name as label,pid,icon,path')->select();
        foreach ($all as $item){
            $item->children = \app\admin\model\Menus::where('pid','=',$item->id)->field('id,name as label,pid,icon,path')->select();
        }

        $data['treeData'] = $all;//节点树
        $data['checkData'] = $nodeIdx;// 选中的
        return json(['code'=>200,'message'=>'成功','data'=>$data]);
    }

    // 更新权限
    public function updateAuth(){
        if(!$this->request->isPost()) return json(['code'=>-1,'message'=>'非法请求','data'=>[]]);
        $id = $this->request->post('role_id',0,'intval');
        $nodeIdx = $this->request->post('nodeIdx/a',[]);

        $find = \app\admin\model\AdminRoleAuth::where('role_id','=',$id)->findOrEmpty();
        if(!$find->isEmpty()){
            $find->menu_idx = implode(',',$nodeIdx);
            $find->update_time = date('Y-m-d H:i:s',time());
            $find->save();
        } else {
            $model = new \app\admin\model\AdminRoleAuth();
            $model->role_id = $id;
            $model->menu_idx = implode(',',$nodeIdx);
            $model->update_time = date('Y-m-d H:i:s',time());
            $model->save();
        }

        return json(['code'=>200,'message'=>'操作成功','data'=>[]]);
    }


}